package com.thrift.client.config;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import java.net.Socket;

/**
 * 客户端连接对象
 * @author 何锦涛--CodeSleep
 * @since 2022/9/4 17:13
 */
public class TTSocket {

    // thrift socket对象
    private TSocket tSocket;
    // 传输对象
    private TTransport tTransport;
    // 协议对象
    private TProtocol tProtocol;

    /**
     * 构造方法初始化各个连接对象
     * @param host server 的地址
     * @param port server 的端口
     */
    public TTSocket(String host, Integer port, String serviceName) {
        tSocket = new TSocket(host, port);
        tTransport = new TFramedTransport(tSocket, 600);
        // 协议对象 这里使用协议对象需要和服务器的一致
        TBinaryProtocol protocol = new TBinaryProtocol(tTransport);
        tProtocol = new TMultiplexedProtocol(protocol, serviceName);
    }

    // 打开通道
    public TTransport open() throws TTransportException {
        if (null != tTransport && !tTransport.isOpen()){
            tTransport.open();
            return tTransport;
        }
        return tTransport;
    }

    // 关闭通道
    public void close() {
        if (null != tTransport && tTransport.isOpen())
            tTransport.close();
    }

    // 判断通道是否是正常打开状态
    public boolean isOpen() {
        Socket socket = tSocket.getSocket();
        return socket.isConnected() && !socket.isClosed();
    }
}

